package org.example.controller;


import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.constraints.Pattern;
import org.example.model.User;
import org.example.service.UserService;
import org.example.utils.JwtUtil;
import org.example.utils.Md5Util;
import org.example.utils.Result;
import org.example.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Validated
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    // 注册
    /**
     * username string 五到十六位非空字符
     * **/
    @PostMapping("/rigister")
    public Result register(@Pattern(regexp = "^\\S{5,18}$") String username, @Pattern(regexp = "\\S{5,16}$") String password) {

        User user = userService.findByUserName(username);

        if (user == null) {
            userService.rigister(username, password);
            return new Result().success();
        } else {
            return new Result().error("用户名已被占用");
        }

    }

    @PostMapping("/login")
    public Result login(@Pattern(regexp = "^\\S{5,18}$") String username, @Pattern(regexp = "\\S{5,16}$") String password) {

        User user = userService.findByUserName(username);

        if (user == null) {
            return new Result().error("用户名不存在");
        }

        // 密码比对
        if (Md5Util.getMD5String(password).equals(user.getPassword())){
            Map<String, Object> map = new HashMap<>();
            map.put("id", user.getId());
            map.put("username", user.getUsername());
            String token = JwtUtil.genToken(map);

            // 将token存redis
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            operations.set(token,token,1, TimeUnit.HOURS);

            return new Result().success( token );
        }
        return new Result().success();

    }

    @GetMapping("/detail")
    public Result Detail() {
        // 获取token中用户信息
        String username = ThreadLocalUtil.getClaimsByKey("username"); // (String)断定返回值为字符串

        User user = userService.findByUserName(username);
        return new Result().success(user);
    }

    @PutMapping("/update")
    public Result updata(@RequestBody @Validated User user) {
        user.setUpdateTime(LocalDateTime.now());
        user.setId(ThreadLocalUtil.getClaimsByKey("id"));
        userService.update(user);
        return new Result().success();
    }

    @PatchMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam String avatarUrl) {
        Number id = ThreadLocalUtil.getClaimsByKey("id");
        LocalDateTime updateTime =   LocalDateTime.now();
        userService.updateAvatar(id, avatarUrl, updateTime);
        return new Result().success();
    }

    @PatchMapping("/updatePassword")
    public Result updatePassword(@RequestBody Map<String, String> parms, @RequestHeader("Authorization") String token) {
        String username = ThreadLocalUtil.getClaimsByKey("username");
        LocalDateTime updateTime =   LocalDateTime.now();
        User user = userService.findByUserName(username);

        if (!StringUtils.hasLength(parms.get("oldPassword"))) {
            return new Result().error("旧密码不能为空");
        }

        if (!StringUtils.hasLength(parms.get("newPassword") )) {
            return new Result().error("新密码不能为空");
        }

        if (!Md5Util.getMD5String(parms.get("oldPassword")).equals(user.getPassword())) {
            return new Result().error("旧密码不正确");
        }

        String newPassword =  Md5Util.getMD5String(parms.get("newPassword"));

        userService.updatePassword(user.getId(), newPassword, updateTime);

        // 更新token
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        RedisOperations<String, String> redisOperations = operations.getOperations(); // 获取redis各个操作方法
        redisOperations.delete(token);

        return new Result().success();
    }
}
